import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cgvc/helper/path_helper.dart';
import 'package:cgvc/helper/permission_helper.dart';
import 'package:cgvc/helper/string_helper.dart';
import 'package:cgvc/page/article_item_widget.dart';
import 'package:cgvc/util/dialog_util.dart';
import 'package:cgvc/util/resource_util.dart';
import 'package:cgvc/util/toast_util.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cgvc/view_model/theme_view_model.dart';
import 'package:cgvc/page/article_item_widget.dart' as prefix0;
import 'package:flutter/rendering.dart';
import 'package:flutter_share_plugin/flutter_share_plugin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

Future<void> showShareAppDialog(BuildContext context, Dialog dialog) async {
  await showDialog(
    context: context,
    builder: (context) {
      return dialog;
    },
  );
}

class ShareDialog extends Dialog {
  final String title;
  final String summary;
  final String notice;
  final String url;
  final String bottomNotice;
  final String fileName;
  final Widget summaryWidget;

  ShareDialog(
    this.title,
    this.summary,
    this.notice,
    this.url,
    this.bottomNotice,
    this.fileName, {
    this.summaryWidget,
  });

  ///关于GlobalKey
  ///https://blog.csdn.net/chunqiuwei/article/details/102868021
  ///可以用来获取state，比如跨组件之间的获取
  final GlobalKey _globalKey = GlobalKey();

  final SaveImageToGallery saveImageToGallery = SaveImageToGallery();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Column(
        //主轴，也就是纵轴方向居中
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ShotImageWidget(
            title,
            summary,
            notice,
            url,
            bottomNotice,
            _globalKey,
            summaryWidget: summaryWidget,
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FloatingActionButton(
                elevation: 0,
                highlightElevation: 0,
                hoverElevation: 0,
                focusElevation: 0,
                disabledElevation: 0,
                tooltip: StringHelper.getS().share,
                backgroundColor: Colors.blue,
                splashColor: Colors.white.withAlpha(50),
                child: Icon(
                  Icons.share,
                  color: Colors.white,
                ),
                onPressed: () => saveImageToGallery.saveImage(
                  context,
                  _globalKey,
                  '/$fileName',
                  share: true,
                ),
              ),
              //间隔空间
              SizedBox(
                width: Platform.isIOS ? 0 : 20,
              ),
              Platform.isIOS
                  ? SizedBox()
                  : FloatingActionButton(
                      elevation: 0,
                      highlightElevation: 0,
                      hoverElevation: 0,
                      focusElevation: 0,
                      disabledElevation: 0,
                      tooltip: StringHelper.getS().downloadImage,
                      backgroundColor: Colors.red,
                      splashColor: Colors.white.withAlpha(50),
                      child: Icon(
                        Icons.file_download,
                        color: Colors.white,
                      ),
                      onPressed: () => saveImageToGallery.saveImage(
                        context,
                        _globalKey,
                        '/$fileName',
                        share: false,
                      ),
                    ),
            ],
          )
        ],
      ),
    );
  }
}

///需要进行截图-RepaintBoundary包裹部分参考
///https://www.codercto.com/a/46348.html
///https://blog.csdn.net/u014449046/article/details/98471268
///https://www.cnblogs.com/wupeng88/p/10797667.html
class ShotImageWidget extends StatelessWidget {
  final String title;
  final String summary;
  final String notice;
  final String url;
  final String bottomNotice;
  final GlobalKey globalKey;
  final Widget summaryWidget;

  ShotImageWidget(
    this.title,
    this.summary,
    this.notice,
    this.url,
    this.bottomNotice,
    this.globalKey, {
    this.summaryWidget,
  });

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: globalKey,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          color: Theme.of(context).cardColor,
          padding: EdgeInsets.only(left: 20, top: 20, right: 20, bottom: 10),
          child: Column(
            //横轴end，只是为了最后的分享的tips文字靠右，其它的组件都通过别的属性靠左对其了
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              //标题
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    //占满这个横轴
                    flex: 1,
                    child: Text(
                      title,
                      textScaleFactor: ThemeViewModel.textScaleFactor,
                      textAlign: TextAlign.justify,
                      style: Theme.of(context).textTheme.headline6.copyWith(
                            fontWeight: FontWeight.bold,
                            letterSpacing: prefix0.letterSpacing,
                            fontSize: 17,
                          ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Container(
                //宽度占满父控件
                width: double.infinity,
                margin: EdgeInsets.only(
                  top: 8,
                ),
                padding: EdgeInsets.symmetric(
                  horizontal: 10,
                  vertical: 12,
                ),
                //圆角线装修器
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  border: Decorations.lineBoxBorder(context,
                      left: true, top: true, right: true, bottom: true),
                ),
                child: Column(
                  //横轴靠左对其
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    //文章摘要，限制最大高度为屏幕的一半
                    ConstrainedBox(
                      constraints: BoxConstraints(
                        maxHeight: MediaQuery.of(context).size.height * 0.5,
                      ),
                      child: SingleChildScrollView(
                        child: summaryWidget ??
                            Text(
                              summary,
                              textScaleFactor: ThemeViewModel.textScaleFactor,
                              //文本超出父控件的依然显示，会溢出父控件，但是有滑动控件，所以可以上下滑动
                              overflow: TextOverflow.visible,
                              strutStyle: StrutStyle(
                                forceStrutHeight: true,
                                height: textLineHeight,
                                leading: leading,
                              ),
                              maxLines: 12,
                              style: Theme.of(context)
                                  .textTheme
                                  .headline6
                                  .copyWith(
                                    fontSize: 13,
                                    letterSpacing: letterSpacing,
                                    color: Theme.of(context)
                                        .textTheme
                                        .headline6
                                        .color
                                        .withOpacity(0.8),
                                  ),
                            ),
                      ),
                    ),
                    //间隔
                    SizedBox(
                      height: 12,
                    ),
                    Row(
                      //垂直居中
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                          //占满剩余空间
                          flex: 1,
                          child: Text(
                            notice,
                            textScaleFactor: ThemeViewModel.textScaleFactor,
                            textAlign: TextAlign.start,
                            style:
                                Theme.of(context).textTheme.headline6.copyWith(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 12,
                                    ),
                          ),
                        ),
                        QrImage(
                          data: url,
                          padding: EdgeInsets.all(2),
                          version: QrVersions.auto,
                          size: 64,
                          foregroundColor:
                              Theme.of(context).textTheme.headline6.color,
                          backgroundColor: Theme.of(context).cardColor,
                        )
                      ],
                    )
                  ],
                ),
              ),

              //圆角分割线包裹内容结束
              SizedBox(
                height: 6,
              ),

              Text(
                bottomNotice,
                textScaleFactor: ThemeViewModel.textScaleFactor,
                textAlign: TextAlign.center,
                style:
                    Theme.of(context).textTheme.caption.copyWith(fontSize: 10),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

//保存图片到系统相册
class SaveImageToGallery {
  //保存的图片路径
  String fileImage;
  Uint8List pngBytes;

  Future<String> getImagePath(String imageName) async {
    String path = await PathHelper.getImagePath();
    File fileImage = File('$path$imageName.png');
    return fileImage.path;
  }

  void saveImage(BuildContext context, GlobalKey globalKey, String imageName,
      {bool share: false}) async {
    if (!TextUtil.isEmpty(fileImage)) {
      if (share) {
        //分享图片
        FlutterShare.shareFileWithText(
          filePath: fileImage,
          textContent: StringHelper.getS().saveImageShareTip,
        );
      } else {
        //图片已经保存下来，不分享，toast提示一下
        ToastUtil.show(
            StringHelper.getS().saveImageSucceedInGallery + '  $fileImage');
      }
      return;
    }

    //先申请权限
    if (!await PermissionHelper.checkStoragePermission()) {
      //拒绝了权限
      ToastUtil.show(StringHelper.getS().saveImagePermissionFailed);
      var value = await DialogUtil.showAlertDialog(
        context,
        title: Platform.isIOS ? 'Freadhub提示' : null,
        content: '分享功能需使用访问您的${Platform.isIOS ? '照片' : '文件读写'}权限',
        cancel: '暂不授权',
        ensure: '去授权',
      );
      if (value == 1) {
        //去应用设置界面
        openAppSettings();
      }
      return;
    }

    //globalKey的作用，跨组件获取RenderRepaintBoundary,用于生成图片
    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject();

    ///弹框宽度与屏幕宽度比值避免截图出来比预览更大
    ///分辨率通过获取设备的devicePixelRatio以达到清晰度良好
    var image = await boundary.toImage(
        pixelRatio: MediaQuery.of(context).devicePixelRatio);

    //转换成png格式二进制
    ByteData byteData = await image.toByteData(format: ImageByteFormat.png);

    //图片数据
    pngBytes = byteData.buffer.asUint8List();

    File saveFile = File(await getImagePath(imageName));
    bool exist = await saveFile.exists() && await saveFile.length() > 0;
    if (!exist) {
      if (!await saveFile.exists()) {
        await saveFile.create();
      }
      File file = await saveFile.writeAsBytes(pngBytes);
      exist = await file.exists();
    }
    if (exist) {
      fileImage = saveFile.absolute.path;
      saveImage(context, globalKey, imageName, share: share);
      return;
    }

    ToastUtil.show(StringHelper.getS().saveImageFailed);
  }
}
